package com.emm.yixun.website.utils;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

import com.emm.yixun.common.model.enums.AnswerTypeEnum;
import com.emm.yixun.website.vo.customer.QuestionAndAnswersVo;
import com.emm.yixun.website.vo.customer.QuestionAnswerVo;
import com.emm.yixun.website.vo.customer.QuestionVo;

public class QuestionnaireToWordUtil {
	
	private static final String UNCHECKED_CHECKBOX = "□";
	private static final String CHECKED_CHECKBOX = "☑";
	private static final String UNCHECKED_RADIO = "○";
	private static final String CHECKED_RADIO = "⊙";
	
	/**
	 * 导出word
	 * @param qaaList
	 * @param response
	 */
	public static void exportWord(QuestionAndAnswersVo qaaVo, HttpServletResponse response) throws Exception{
		//生成Word文档
		XWPFDocument doc = new XWPFDocument();
		String title = qaaVo.getTitle();
		String desc = qaaVo.getDesc();
		List<QuestionVo> questionList = qaaVo.getQuestionList();
		//添加问卷标题
		XWPFParagraph paragraph = writeToParagraph(doc, ParagraphAlignment.CENTER);
		Map<String, String> contentMap = new HashMap<String, String>();
		contentMap.put("title", title);
		setParagraphRun(paragraph, contentMap, 20, 20, true);
		//添加问卷描述
		paragraph = writeToParagraph(doc, ParagraphAlignment.LEFT);
		contentMap = new HashMap<String, String>();
		contentMap.put("desc", "    " + desc);
		setParagraphRun(paragraph, contentMap, 13, 13, true);
		//添加题目、题目描述及选项
		if(null != questionList && questionList.size() > 0){
			for(QuestionVo questionVo: questionList){
				String question = questionVo.getQuestion();
				String questionDesc = questionVo.getQuestionDesc();
				String problemCode = questionVo.getProblemCode();
				String answerType = questionVo.getAnswerType();
				List<QuestionAnswerVo> qaList = questionVo.getQuestionAnswerList();
				paragraph = writeToParagraph(doc, ParagraphAlignment.LEFT);
				contentMap = new HashMap<String, String>();
				contentMap.put("question", problemCode + "  " + question);
				setParagraphRun(paragraph, contentMap, 15, 15, true);
				paragraph = writeToParagraph(doc, ParagraphAlignment.LEFT);
				contentMap = new HashMap<String, String>();
				contentMap.put("questionDesc", "  " + questionDesc);
				setParagraphRun(paragraph, contentMap, 13, 13, false);
				int rows = 1;
				int cols = 1;
				boolean needBorder = true;
				//非文本框,选项一行放4个
				if(!AnswerTypeEnum.INPUT.getNo().equals(answerType)){
					rows = qaList.size() / 4;
					if(qaList.size() % 4 != 0){
						rows += 1;
					}
					cols = 4;
					needBorder = false;
				}
				writeToTable(doc, qaList, rows, cols, needBorder, answerType);
			}
		}
		
//		 FileOutputStream out1 = new FileOutputStream("D:\\temp\\simple.docx");
//		 doc.write(out1);
//		 out1.close();
		 
		 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		 String mimetype = "application/x-msdownload";
		 String downFileName = df.format(new Date()) + ".docx";
		 String inlineType = "attachment";
		 response.setHeader("Content-Disposition", inlineType
				+ ";filename=\"" + downFileName + "\"");
		 OutputStream out = response.getOutputStream();
		 response.setContentType(mimetype);
		 doc.write(out);
		 out.close();
	}
  
  	/**
  	 * word表格操作
  	 *
  	 * @param doc
  	 */
	public static void writeToTable(XWPFDocument doc, List<QuestionAnswerVo> qaVoList, int rows, int cols, boolean needBorder, String answerType){
		XWPFTable table = doc.createTable(rows, cols);
		if(!needBorder){
			tableWithOutBorder(table);
		}
		//表格宽度
		CTTbl ttbl = table.getCTTbl();  
        CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();  
        CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();  
        tblWidth.setW(new BigInteger("8000"));  
        tblWidth.setType(STTblWidth.DXA); 
		
	    // 设置上下左右四个方向的距离，可以将表格撑大
	    table.setCellMargins(20, 20, 20, 20);
	    for(int ii=0; ii<rows; ii++){
    		List<XWPFTableCell> cells = table.getRow(ii).getTableCells();
    		for(int jj=0; jj< cols; jj++){
    			int index = (ii*cols)+jj;
    			if(index >= qaVoList.size()){
    				break;
    			}
    			String text = qaVoList.get(index).getAnswer();
    			String chooseType = "";
    			String space = "";
    			if(AnswerTypeEnum.RADIO.getNo().equals(answerType)){
    				chooseType = UNCHECKED_RADIO;
    				space = "    ";
    			}else if(AnswerTypeEnum.CHECKBOX.getNo().equals(answerType)){
    				chooseType = UNCHECKED_CHECKBOX;
    				space = "    ";
    			}else if(AnswerTypeEnum.INPUT.getNo().equals(answerType)){
    				text = "";
    			}
    			if("select_other".equals(text.trim())){
    				text = "其他: ";
    			}
   	    	 	cells.get(jj).setText(chooseType + space + text);
    		}
    	}
	}
	
	/**
	 * 表格无边框
	 * @param table
	 */
	public static void tableWithOutBorder(XWPFTable table){
		CTTblBorders borders=table.getCTTbl().getTblPr().addNewTblBorders();  
        CTBorder hBorder=borders.addNewInsideH();  
        hBorder.setVal(STBorder.Enum.forString("none"));  
        hBorder.setSz(new BigInteger("1"));  
        hBorder.setColor("0000FF");  

        CTBorder vBorder=borders.addNewInsideV();  
        vBorder.setVal(STBorder.Enum.forString("none"));  
        vBorder.setSz(new BigInteger("1"));  
        vBorder.setColor("00FF00");  

        CTBorder lBorder=borders.addNewLeft();  
        lBorder.setVal(STBorder.Enum.forString("none"));  
        lBorder.setSz(new BigInteger("1"));  
        lBorder.setColor("3399FF");  

        CTBorder rBorder=borders.addNewRight();  
        rBorder.setVal(STBorder.Enum.forString("none"));  
        rBorder.setSz(new BigInteger("1"));  
        rBorder.setColor("F2B11F");  

        CTBorder tBorder=borders.addNewTop();  
        tBorder.setVal(STBorder.Enum.forString("none"));  
        tBorder.setSz(new BigInteger("1"));  
        tBorder.setColor("C3599D");  

        CTBorder bBorder=borders.addNewBottom();  
        bBorder.setVal(STBorder.Enum.forString("none"));  
        bBorder.setSz(new BigInteger("1"));  
        bBorder.setColor("F7E415");  
	}
	
	/**
  	 * word段落
  	 *
  	 * @param doc
  	 */
	public static XWPFParagraph writeToParagraph(XWPFDocument doc, ParagraphAlignment align){
		// 设置字体对齐方式
	    XWPFParagraph paragraph = doc.createParagraph();
	    paragraph.setAlignment(align);
	    paragraph.setVerticalAlignment(TextAlignment.TOP);
	    return paragraph;
	}
	
	/**
	 * 设置位子属性
	 * @param paragraph 段落
	 * @param contentMap 内容
	 * @param fontSize 文字大小
	 * @param position 上下间距
	 * @param isBold 是否加粗
	 */
	public static void setParagraphRun(XWPFParagraph paragraph, Map<String, String> contentMap, int fontSize,
				int position, boolean isBold){
		// 第一页要使用p1所定义的属性
	    XWPFRun run = paragraph.createRun();
	    // 设置使用何种字体
	    run.setFontFamily("Courier");
	    //字体大小
	    run.setFontSize(fontSize);
	    // 设置字体是否加粗
	    run.setBold(isBold);
	    // 设置上下两行之间的间距
	    run.setTextPosition(position);
	    for(String values: contentMap.values()){
	    	run.setText(values + "\t");
	    }
	    
	}
	
	/**
	   * sd
	   */
	public static void main(String[] args) throws Exception {
		System.out.println("select other".startsWith("select"));
	}
}
